package mx.ipn.presentacion.facturacion;

import mx.ipn.presentacion.facturacion.ui.*;
import mx.ipn.presentacion.ConexionConNegocios;
import com.trolltech.qt.gui.QMessageBox;
import com.trolltech.qt.gui.QApplication;
import com.trolltech.qt.gui.QTableWidgetItem;
import com.trolltech.qt.gui.QWidget;
import com.trolltech.qt.gui.QDialog;
import mx.ipn.to.*;

import java.util.*;
public class FacturaP extends QWidget{
	Ui_factura fact;
	FacturaTO  facturato;
	FacturaTO  []arrfacturato;
	DetalleFacturaTO detalle;
	DetalleFacturaTO []adetalle;
	DetalleFacturaTO []arrdetalle;
	BitacoraSTO[] servicios;
	ClienteTO[] cliente;
	QTableWidgetItem newItem=null;
	QTableWidgetItem concepto=null;
	QTableWidgetItem costo=null;
	int filas=0;
	int idFactura; 
	String nota;
	String rfc;
	java.util.Date fecha;
	double iva=0.0;
	double tarifa=0.0;
	double total=0.0;
	int idOperacion;
	Double val;
	int idserv=0;
	int bandera = -1;
	GregorianCalendar f1 = new GregorianCalendar();
	String contenido = "<html>" +
    "<head><style type=\"text/css\">" +
    "<!--" +
    ".Estilo1 {" +
    "	font-family: Arial, Helvetica, sans-serif;" +
    "	color: #000066;" +
    "}" +
    ".Estilo2 {color: #990000}" +
    "-->" +
    "</style></head><body>";
   String tabla="";
   String renglon ="";
   String totales="";
	public static void main(String[] args) {
		QApplication.initialize(args);
		FacturaP p = new FacturaP();
		QApplication.exec();
	}
	
	public FacturaP(){
		fact = new Ui_factura();
		fact.setupUi(this);
		fact.tableWidget_3.setRowCount(5);
		fact.pushButton.clicked.connect(this,"nueva()");
		fact.pushButton_2.clicked.connect(this,"modificar()");
		fact.pushButton_3.clicked.connect(this,"imprime()");
		fact.pushButton_4.clicked.connect(this,"agregar()");
		fact.pushButton_5.clicked.connect(this,"buscarfactura()");
		fact.pushButton_6.clicked.connect(this,"guardar()");
		fact.pushButton_7.clicked.connect(this,"eliminarfactura()");
		fact.pushButton_8.clicked.connect(this,"eliminar()");
		fact.pushButton_9.clicked.connect(this,"buscarfc()");
		fact.pushButton_10.clicked.connect(this,"reporte()");
		fact.tableWidget_3.itemClicked.connect(this,"selectServicio()");
//		ConexionConNegocios.inicializar();
//		inicia();
		this.show();
	}

	public FacturaP(QWidget parent){
	}
	public void imprime(){
		 tabla="<h1 align=\"center\" class=\"Estilo1\">Factura</h1>" +
		 		"<p align=\"left\"><strong>Numero:</strong> sadasdasdasdasa </p>" +
		 		"<p align=\"left\"><strong>Fecha:</strong> "+ fact.dateEdit.text() +" </p>" +
		 		"<p align=\"left\"><strong>Cliente:</strong> "+fact.lineEdit_4.text() +" </p>" +
		 		"<p align=\"left\"><strong>RFC:</strong> "+fact.lineEdit_5.text() +" </p>" +
		 		"<p align=\"left\"><strong>Nota:</strong> "+fact.lineEdit_6.text() +" </p>" +
		 		"<p align=\"left\">&nbsp;</p>" +
		 	"<table width=\"731\" height=\"83\" border=\"1\" align=\"center\" bordercolor=\"#999999\">" +
			"  <tr> <th scope=\"col\"><span class=\"Estilo2\">Factura</span></th>" +
			"<th scope=\"col\"><span class=\"Estilo2\">RFC</span></th>" +
			"<th scope=\"col\"><span class=\"Estilo2\">Operacion</span></th>" +
			"<th scope=\"col\"><span class=\"Estilo2\">Observaciones</span></th>" +
			"<th scope=\"col\"><span class=\"Estilo2\">Tarifa</span></th>" +
			"</tr>";
		contenido = contenido + tabla;
		contenido = contenido + renglon;
		contenido = contenido + totales;
		View ver = new View(contenido);
	}
	public void inicia(){
        UsuarioTO usuarioTO = new UsuarioTO();
		
		usuarioTO.setNombreUsuario("contra5");
		usuarioTO.setContrasenia("pass5");
		
		UsuarioTO resp = null;
		
		resp = (UsuarioTO) ConexionConNegocios.invocaServicio("login", usuarioTO, UsuarioTO.class);
	}
	public  static boolean isNumeric(String cadena){
		try {
			Integer.parseInt(cadena);
			return true;
		} catch (NumberFormatException nfe){
			return false;
		}
	}
	public boolean valida(){
		boolean valido=false;
		if(fact.lineEdit_4.text().compareToIgnoreCase("")!=0){
			if(fact.lineEdit_5.text().compareToIgnoreCase("")!=0){
				if(fact.lineEdit_6.text().compareToIgnoreCase("")!=0){
					if(fact.lineEdit_7.text().compareToIgnoreCase("")!=0){
						if(fact.lineEdit_8.text().compareToIgnoreCase("")!=0){
							valido=true;
						}
					}	
				}	
			}
		}
		return valido;
	}
	public void nueva(){
		bandera=2; // se guardara nueva factura
		limpia();
		habilita();
	}
	public void limpia(){
		 fact.lineEdit.setText("");
		 fact.lineEdit_2.setText("");
		 fact.lineEdit_4.setText("");
		 fact.lineEdit_5.setText("");
		 fact.lineEdit_6.setText("");
		 fact.lineEdit_7.setText("");
		 fact.lineEdit_8.setText("");
		 fact.tableWidget_3.clear();	
	} 
	public void habilita()
	{
		fact.lineEdit.setEnabled(true);
		fact.lineEdit_2.setEnabled(true);
		fact.lineEdit_4.setEnabled(true);
		fact.lineEdit_5.setEnabled(true);
		fact.lineEdit_6.setEnabled(true);
		fact.lineEdit_7.setEnabled(true);
		fact.lineEdit_8.setEnabled(true);
		fact.dateEdit.setEnabled(true);
		fact.tableWidget_3.setEnabled(true);
		fact.pushButton_3.setEnabled(true);
		fact.pushButton_4.setEnabled(true);
		fact.pushButton_6.setEnabled(true);
		fact.pushButton_7.setEnabled(true);
		fact.pushButton_8.setEnabled(true);
		fact.pushButton_9.setEnabled(true);
	}
	public void deshabilita()
	{
		 fact.lineEdit.setEnabled(false);
		 fact.lineEdit_2.setEnabled(false);
		 fact.lineEdit_4.setEnabled(false);
		 fact.lineEdit_5.setEnabled(false);
		 fact.lineEdit_6.setEnabled(false);
		 fact.lineEdit_7.setEnabled(false);
		 fact.lineEdit_8.setEnabled(false);
		 fact.dateEdit.setEnabled(false);
		 fact.tableWidget_3.setEnabled(false);
		 fact.pushButton_3.setEnabled(false);
		 fact.pushButton_4.setEnabled(false);
		 fact.pushButton_6.setEnabled(false);
		 fact.pushButton_7.setEnabled(false);
		 fact.pushButton_8.setEnabled(false);	
		 fact.pushButton_9.setEnabled(false);
	}
	public void buscarfc()
	{
		SelectPrefactura sp = new SelectPrefactura();
		if(sp.exec()== QDialog.DialogCode.Accepted.value()){
			 fact.lineEdit_4.setText(sp.denominacion);
			 fact.lineEdit_5.setText(sp.rfc);
		}
	}
	public void reporte(){
		Reporte rep= new Reporte();
	}
	public int buscarservicio(int idoperacion)
	{
		int pos= -1;
		for(int j=0;j<(servicios.length);j++){

			 System.out.println(servicios[j].getIdOperacion()+ "vs"+ idoperacion);
			 if(servicios[j].getIdOperacion()==idoperacion)
				 pos=j;
		}
		return pos;
	}
	public void llena(FacturaTO factura){
		int i=0;
		int pos=-1;
		int idfactura=factura.getIdFactura();
		 fact.lineEdit.setText(factura.getNota());
		 fact.lineEdit_2.setText(String.valueOf(factura.getIdFactura()));
		 fact.lineEdit_5.setText(factura.getRegistro());
		 fact.lineEdit_6.setText(String.valueOf(factura.getTarifa()));
		 fact.lineEdit_7.setText(String.valueOf(factura.getIva()));
		 fact.lineEdit_8.setText(String.valueOf(factura.getTotal()));
		 arrdetalle=(DetalleFacturaTO[])ConexionConNegocios.invocaServicio("selectDetalleFactura",DetalleFacturaTO[].class);
		 if(arrdetalle!=null)
		 {
			 servicios = (BitacoraSTO[]) ConexionConNegocios.invocaServicio("verServicios",BitacoraSTO[].class);
			 if(servicios!=null){
				 fact.tableWidget_3.clearContents();
			    for(int j=0;j<(arrdetalle.length);j++){
				   if(arrdetalle[j].getIdFactura()==idfactura){ 
				      if((pos=buscarservicio(arrdetalle[j].getIdOperacion()))!=-1)
				      {
					  if(fact.tableWidget_3.rowCount()==0)
						  fact.tableWidget_3.setRowCount(5);
					  newItem = new QTableWidgetItem(String.valueOf(servicios[pos].getIdOperacion()));
					  fact.tableWidget_3.setItem(i,0,newItem);
					  newItem = new QTableWidgetItem(String.valueOf(servicios[pos].getObservaciones()));
					  fact.tableWidget_3.setItem(i,1,newItem);
					  newItem = new QTableWidgetItem(String.valueOf(servicios[pos].getCostoEstimado()));
					  fact.tableWidget_3.setItem(i,2,newItem);
					  i++;
					  renglon = renglon + "<tr><td>"+ idfactura+"</td>" +
	    	    		"<td>" + factura.getRegistro()+"</td>" +
	    	    		"<td>" + servicios[pos].getIdOperacion()+"</td>" +
	    	    		"<td>" + servicios[pos].getObservaciones()+"</td>" +
	    	    		"<td>" + servicios[pos].getCostoEstimado()+"</td>" +
	    	    		"</tr>";
				      }
			       }
			    }
			 }
		 }
	}
	public void buscarfactura()
	{
		tabla="";
    	renglon ="";
    	totales="";
		renglon="";
		VerFactura ver = new VerFactura();
		if(ver.exec()== QDialog.DialogCode.Accepted.value()){
			if(ver.facturato!=null)
		    llena(ver.facturato);
			fact.pushButton_2.setEnabled(true);
		}
	}
	public void modificar(){
		bandera=1; //se guardaran modificaciones
		habilita();
	}
	public void eliminarfactura()
	{
		if(fact.lineEdit_2.text().compareToIgnoreCase("")!=0)
		{
		int idf =Integer.parseInt(fact.lineEdit_2.text());
		    short r =((Short)ConexionConNegocios.invocaServicio("borraFactura",idf,Short.class)).shortValue();
		    short r1 =((Short)ConexionConNegocios.invocaServicio("eliminaDetalleFactura",idf,Short.class)).shortValue();
		    if(r==1){
				 QMessageBox.information(null,"informacion","eliminada");
				 limpia();
			     deshabilita();}
			else{
				 QMessageBox.critical(null, "Error",
							"No se borro nungun dato.",
							QMessageBox.StandardButton.Ok,
							QMessageBox.StandardButton.Ok);}
		}
	}
	public void agregar(){
		if(fact.lineEdit_5.text().compareToIgnoreCase("")!=0)
		{
			Prefactura p = new Prefactura("tme840315kt6");
			if(p.exec()== QDialog.DialogCode.Accepted.value()){
			   newItem = Prefactura.itemservicio ;
			   concepto = Prefactura.itemconcepto ;
			   costo = Prefactura.itemcosto ;
			  if(newItem==null){
				System.out.println("nulo");}
			  else{
				  if(fact.tableWidget_3.rowCount()==0)
					  fact.tableWidget_3.setRowCount(5);
				fact.tableWidget_3.insertRow(filas);
				fact.tableWidget_3.setItem(filas,0,newItem);
			    fact.tableWidget_3.setItem(filas,1,concepto);
			    fact.tableWidget_3.setItem(filas,2,costo);
			    filas++;
				System.out.println("bueno");
			    System.out.println(newItem.text());
			    /***calcula totales****/
			    iva=0.0;
				tarifa=0.0;
				total=0.0;
			    int cont = fact.tableWidget_3.rowCount();
				 for(int i=0;i<cont;i++){
				 	newItem = fact.tableWidget_3.item(i,2);
				 	if(newItem!=null){
				 		if(newItem.text().compareToIgnoreCase("")!=0){
				 		val=new Double(newItem.text());
				 		tarifa = tarifa+val.doubleValue();
				 		} 
				 	}
				 }
				 iva = tarifa*0.15;
				 total = tarifa+iva;
				 fact.lineEdit_6.setText(String.valueOf(tarifa));
				 fact.lineEdit_7.setText(String.valueOf(iva));
				 fact.lineEdit_8.setText(String.valueOf(total));
				 totales="<tr bordercolor=\"#FFFFFF\">" +
					"<td>&nbsp;</td>" +
					"<td>&nbsp;</td>" +
					"<td>&nbsp;</td>" +
					"<td>&nbsp;</td>" +
					"<td>&nbsp;</td>" +
					"</tr>" +
					"<tr>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td>Total</td>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"</tr>" +
					"<tr>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td>Importe</td>" +
					"<td>"+tarifa+"</td></tr>" +
					"<tr>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td>Iva</td>" +
					"<td>"+iva+"</td>" +
					"</tr>" +
					"<tr>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td bordercolor=\"#FFFFFF\">&nbsp;</td>" +
					"<td>Total</td>" +
					"<td>"+total+"</td>" +
					"</tr>" +
					"</table>" +
					"<p align=\"left\">&nbsp;</p>" +
					"<p align=\"left\">&nbsp;</p>" +
					"</body>" +
					"</html>";
			    }
			}
		}
	}
	public void eliminar()
	{
		int fila = fact.tableWidget_3.currentRow();
		fact.tableWidget_3.removeRow(fila);
		filas--;
		iva=0.0;
		tarifa=0.0;
		total=0.0;
		int cont = fact.tableWidget_3.rowCount();
		 for(int i=0;i<cont;i++){
		 	newItem = fact.tableWidget_3.item(i,2);
		 	if(newItem!=null){
		 		if(newItem.text().compareToIgnoreCase("")!=0){
		 		val=new Double(newItem.text());
		 		tarifa = tarifa+val.doubleValue();
		 		} 
		 	}
		 }
		 iva = tarifa*0.15;
		 total = tarifa+iva;
		 fact.lineEdit_6.setText(String.valueOf(tarifa));
		 fact.lineEdit_7.setText(String.valueOf(iva));
		 fact.lineEdit_8.setText(String.valueOf(total));
	}
	public void selectServicio(){
		QTableWidgetItem newItem=null;
		int fila = fact.tableWidget_3.currentRow();
		newItem = fact.tableWidget_3.item(fila,0);
		idserv= Integer.parseInt(newItem.text());
		fact.lineEdit_2.setText(String.valueOf(idserv));
	}
	public void guardar()
	{
		/*leer id_cliente rfc de la tabla cliente_rfc
		 * leer el id_operacion de la bitacora de servicio
		 * lista los serviicos y selecciona los que tienen id cliente
		 * considerado= false
		 * y guardar
		 * */
		Object []arg=new Object[2];
		int cont = fact.tableWidget_3.rowCount();
		int idfactura;
		adetalle = new DetalleFacturaTO [cont];
		if(valida()){
		   for(int i=0;i<cont;i++){
		 	  newItem = fact.tableWidget_3.item(i,2);
		 	  if(newItem!=null){
		 		  if(newItem.text().compareToIgnoreCase("")!=0){
		 		  val=new Double(newItem.text());
		 		  tarifa = tarifa+val.doubleValue();
		 		  newItem = fact.tableWidget_3.item(i,0);
		 		  idOperacion = Integer.parseInt(newItem.text());
		 		  detalle = new DetalleFacturaTO(0,0,idOperacion);
		 		  adetalle[i]=detalle;
		 		  } 
		 	  }
		   }
		   iva = tarifa*0.15;
		   total = tarifa+iva;
		   fact.lineEdit_6.setText(String.valueOf(tarifa));
		   fact.lineEdit_7.setText(String.valueOf(iva));
		   fact.lineEdit_8.setText(String.valueOf(total));
		   nota= fact.lineEdit.text();
		   rfc= fact.lineEdit_5.text();
		   f1.set(fact.dateEdit.date().year(),(fact.dateEdit.date().month()-1),fact.dateEdit.date().day());
		   fecha=f1.getTime();
		   facturato = new FacturaTO(0,nota,rfc,fecha,iva,tarifa,total);
		   if(bandera==2){
		      boolean flag=((Boolean)ConexionConNegocios.invocaServicio("crearFactura",facturato,Boolean.class)).booleanValue();
		      arrfacturato=(FacturaTO[])ConexionConNegocios.invocaServicio("selectFactura",FacturaTO[].class);
		      idfactura= arrfacturato[(arrfacturato.length)-1].getIdFactura();
		      for(int j=0;j<adetalle.length;j++){
		    	  if(adetalle[j]!=null){
		    		  adetalle[j].setIdFactura(idfactura);
		    		  boolean flag1=((Boolean)ConexionConNegocios.invocaServicio("crearDetalleFactura",adetalle[j],Boolean.class)).booleanValue();
		    		  if(flag1){
		    			  arg[0]=adetalle[j].getIdOperacion();
		    			  arg[1]=true;
		    			  short res=((Short)ConexionConNegocios.invocaServicio("setConsiderado",arg,Short.class)).shortValue();
		    		  }
		    	  }
		      }
		      if(flag){
			     QMessageBox.information(null,"informacion","guardada");
		         deshabilita();
		         bandera=-1;}
		      else{
			      QMessageBox.critical(null, "Error",
						"No guardaron los datos.",
						QMessageBox.StandardButton.Ok,
						QMessageBox.StandardButton.Ok);}
		   }
		   if(bandera==1){
			   if(QMessageBox.question(null,"Informacion","¿Esta seguro de guardar cambios?",QMessageBox.StandardButton.Ok, QMessageBox.StandardButton.No)== QMessageBox.StandardButton.Ok.value()){
			      short r=((Short)ConexionConNegocios.invocaServicio("updateFactura",facturato,Short.class)).shortValue();
			      if(r==1){
			    	  short r1 =((Short)ConexionConNegocios.invocaServicio("eliminaDetalleFactura",facturato.getIdFactura(),Short.class)).shortValue();
			    	  for(int j=0;j<adetalle.length;j++){
				    	  if(adetalle[j]!=null){
				    		  adetalle[j].setIdFactura(facturato.getIdFactura());
				    		  boolean flag1=((Boolean)ConexionConNegocios.invocaServicio("crearDetalleFactura",adetalle[j],Boolean.class)).booleanValue();
				    		  if(flag1){
				    			  arg[0]=adetalle[j].getIdOperacion();
				    			  arg[1]=true;
				    			  short res=((Short)ConexionConNegocios.invocaServicio("setConsiderado",arg,Short.class)).shortValue();
				    		  }
				    	  }
				      }
				     QMessageBox.information(null,"informacion","guardada");
			         deshabilita();
			         bandera=-1;}
			      else{
				      QMessageBox.critical(null, "Error",
							"No guardaron los datos.",
							QMessageBox.StandardButton.Ok,
							QMessageBox.StandardButton.Ok);}
			   }
			}
	   }
	   else{
		      QMessageBox.critical(null, "Error",
					"Faltan llenar campos",
					QMessageBox.StandardButton.Ok,
					QMessageBox.StandardButton.Ok);}
	}
}

